import { useState, useEffect, useRef } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { 
  Upload, 
  Download, 
  Search, 
  Filter,
  FileSpreadsheet,
  Database,
  Globe,
  CheckCircle,
  AlertCircle,
  Clock,
  ArrowLeft,
  ExternalLink,
  Eye,
  RefreshCw
} from 'lucide-react'
import { toast } from 'sonner'
import apiService from '../services/api'
import AIAnalysisDisplay from './AIAnalysisDisplay'
import DemoModeAlert from './DemoModeAlert'

// 板块配置
const SECTORS = {
  pharma_formulations: { name: '人药制剂板块', icon: '💊', color: 'bg-blue-500' },
  pharma_apis: { name: '人药原料药板块', icon: '🧪', color: 'bg-green-500' },
  plant_protection: { name: '植保板块', icon: '🌱', color: 'bg-emerald-500' },
  animal_health: { name: '动保板块', icon: '🐾', color: 'bg-purple-500' }
}

export default function DataManagement() {
  const [uploadProgress, setUploadProgress] = useState(0)
  const [isUploading, setIsUploading] = useState(false)
  const [searchTerm, setSearchTerm] = useState('')
  const [historicalData, setHistoricalData] = useState([])
  const [industryData, setIndustryData] = useState([])
  const [sectorsData, setSectorsData] = useState({})
  const [businessUnits, setBusinessUnits] = useState([])
  const [metrics, setMetrics] = useState([])
  const [loading, setLoading] = useState(false)
  const [selectedSector, setSelectedSector] = useState(null)
  const [activeTab, setActiveTab] = useState('historical')
  const [hoveredReference, setHoveredReference] = useState(null)
  const [hoveredSentence, setHoveredSentence] = useState(null)
  const [tooltipPosition, setTooltipPosition] = useState({ x: 0, y: 0 })
  const hoverTimeoutRef = useRef(null)
  const [filters, setFilters] = useState({
    business_unit: '',
    metric_name: '',
    year: ''
  })
  const [sortConfig, setSortConfig] = useState({ key: null, direction: 'asc' })
  const [showDemoAlert, setShowDemoAlert] = useState(false)
  const [currentPage, setCurrentPage] = useState(1)
  const [itemsPerPage] = useState(20)
  const fileInputRef = useRef(null)

  // 格式化时间显示函数
  const formatDateTime = (dateString) => {
    if (!dateString) return '暂无数据'
    
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    
    return `${year}年${month}月${day}日 ${hours}:${minutes}`
  }

  // 计算智能提示框位置
  const calculateTooltipPosition = (element) => {
    if (!element) return { x: 0, y: 0 }
    
    const rect = element.getBoundingClientRect()
    const scrollX = window.pageXOffset || document.documentElement.scrollLeft
    const scrollY = window.pageYOffset || document.documentElement.scrollTop
    
    // 提示框尺寸估算
    const tooltipWidth = 320  // max-w-md 约等于 320px
    const tooltipHeight = 150 // 估算高度
    
    // 计算基础位置（圆点中心）
    const centerX = rect.left + rect.width / 2
    const centerY = rect.top + rect.height / 2
    
    // 获取视窗尺寸
    const viewportWidth = window.innerWidth
    const viewportHeight = window.innerHeight
    
    let x = centerX + scrollX
    let y = centerY + scrollY
    
    // 水平位置调整
    if (centerX + tooltipWidth > viewportWidth - 20) {
      // 右侧空间不足，放在左侧
      x = centerX + scrollX - tooltipWidth - 10
    } else {
      // 右侧空间充足，放在右侧
      x = centerX + scrollX + 10
    }
    
    // 垂直位置调整
    if (centerY + tooltipHeight > viewportHeight - 20) {
      // 下方空间不足，放在上方
      y = centerY + scrollY - tooltipHeight - 10
    } else {
      // 下方空间充足，放在下方
      y = centerY + scrollY + 10
    }
    
    // 确保不会超出屏幕边界
    x = Math.max(10, Math.min(x, viewportWidth - tooltipWidth - 10))
    y = Math.max(10, Math.min(y, viewportHeight - tooltipHeight - 10))
    
    return { x, y }
  }

  // 防抖处理引用悬停
  const handleReferenceHover = (referenceData, mouseEvent) => {
    // 清除之前的定时器
    if (hoverTimeoutRef.current) {
      clearTimeout(hoverTimeoutRef.current)
    }
    
    // 使用鼠标位置作为提示框位置，并确保不超出屏幕边界
    const tooltipWidth = 320  // 浮框宽度
    const tooltipHeight = 150 // 浮框高度
    const viewportWidth = window.innerWidth
    const viewportHeight = window.innerHeight
    
    let x = mouseEvent.clientX + 10 // 鼠标右侧10px
    let y = mouseEvent.clientY - 10 // 鼠标上方10px
    
    // 如果右侧空间不足，放在左侧
    if (x + tooltipWidth > viewportWidth - 20) {
      x = mouseEvent.clientX - tooltipWidth - 10
    }
    
    // 如果上方空间不足，放在下方
    if (y < 20) {
      y = mouseEvent.clientY + 20
    }
    
    // 如果下方空间不足，放在上方
    if (y + tooltipHeight > viewportHeight - 20) {
      y = mouseEvent.clientY - tooltipHeight - 10
    }
    
    // 确保不会超出屏幕边界
    x = Math.max(10, Math.min(x, viewportWidth - tooltipWidth - 10))
    y = Math.max(10, Math.min(y, viewportHeight - tooltipHeight - 10))
    
    const position = { x, y }
    setTooltipPosition(position)
    
    // 立即设置引用信息
    setHoveredReference(referenceData)
    
    // 延迟设置句子高亮，避免频繁切换
    hoverTimeoutRef.current = setTimeout(() => {
      setHoveredSentence(referenceData?.sentenceIndex)
    }, 150) // 150ms延迟
  }

  const handleReferenceLeave = () => {
    // 清除定时器
    if (hoverTimeoutRef.current) {
      clearTimeout(hoverTimeoutRef.current)
    }
    
    // 延迟清除，给用户时间移动到相邻引用
    hoverTimeoutRef.current = setTimeout(() => {
      setHoveredReference(null)
      setHoveredSentence(null)
    }, 100) // 100ms延迟
  }

  useEffect(() => {
    loadIndustryData()
    loadSectorsData()
    loadHistoricalData()
    loadMetadata()
  }, [])

  // 清理定时器
  useEffect(() => {
    return () => {
      if (hoverTimeoutRef.current) {
        clearTimeout(hoverTimeoutRef.current)
      }
    }
  }, [])





  const loadIndustryData = async () => {
    try {
      const response = await apiService.getIndustryData({ page: 1, page_size: 10 })
      const items = response.data?.items || []
      
      setIndustryData(items.map(item => ({
        id: item.id,
        source: item.source,
        title: item.title,
        date: item.publish_date || item.created_at,
        status: 'updated'
      })))
    } catch (error) {
      console.error('加载行业数据失败:', error)
      // 使用模拟数据作为后备
      setIndustryData([
        { id: 1, source: '国家统计局', title: '2024年医药制造业统计数据', date: '2024-01-15', status: 'updated' },
        { id: 2, source: '中国医药工业信息中心', title: '医药行业发展报告', date: '2024-01-10', status: 'crawling' },
        { id: 3, source: '证券研究报告', title: '医药板块投资分析', date: '2024-01-08', status: 'failed' }
      ])
    }
  }

  // 加载历史数据
  const loadHistoricalData = async () => {
    try {
      setLoading(true)
      const response = await apiService.getHistoricalData(filters)
      if (response.code === 200) {
        setHistoricalData(response.data.records || [])
      }
    } catch (error) {
      console.error('加载历史数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  // 加载业务单元和指标
  const loadMetadata = async () => {
    try {
      const [unitsResponse, metricsResponse] = await Promise.all([
        apiService.getBusinessUnits(),
        apiService.getMetrics()
      ])
      
      if (unitsResponse.code === 200) {
        setBusinessUnits(unitsResponse.data || [])
      }
      
      if (metricsResponse.code === 200) {
        setMetrics(metricsResponse.data || [])
      }
    } catch (error) {
      console.error('加载元数据失败:', error)
    }
  }

  const loadSectorsData = async () => {
    try {
      setLoading(true)
      // 使用ApiService统一管理API调用
      const result = await apiService.getSectorsData()
      
      if (result.code === 200) {
        setSectorsData(result.data.sectors)
      }
    } catch (error) {
      console.error('加载板块数据失败:', error)
      toast.error('加载板块数据失败')
    } finally {
      setLoading(false)
    }
  }

  const handleFileUpload = async (event) => {
    const file = event.target.files[0]
    if (!file) return

    setIsUploading(true)
    setUploadProgress(0)

    try {
      // 模拟上传进度
      const progressInterval = setInterval(() => {
        setUploadProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval)
            return 90
          }
          return prev + 10
        })
      }, 200)

      await apiService.importData(file)
      
      clearInterval(progressInterval)
      setUploadProgress(100)
      
      toast.success('数据导入成功')
      loadHistoricalData() // 重新加载数据
    } catch (error) {
      console.error('文件上传失败:', error)
      toast.error(error.message || '文件上传失败')
    } finally {
      setIsUploading(false)
      setUploadProgress(0)
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
      }
    }
  }

  const handleStartCrawl = async () => {
    try {
      // 使用ApiService统一管理API调用
      const result = await apiService.startCrawlTask({})
      
      if (result.code === 200) {
        toast.success('行业数据查询任务已启动，正在后台异步执行')
        setTimeout(() => loadSectorsData(), 2000) // 2秒后刷新数据
      } else {
        toast.error('启动查询任务失败')
      }
    } catch (error) {
      console.error('启动查询任务失败:', error)
      toast.error('启动查询任务失败')
    }
  }

  const getStatusIcon = (status) => {
    switch (status) {
      case 'verified':
      case 'updated':
      case 'completed':
        return <CheckCircle className="h-4 w-4 text-green-500" />
      case 'pending':
      case 'crawling':
      case 'running':
        return <Clock className="h-4 w-4 text-yellow-500" />
      case 'failed':
        return <AlertCircle className="h-4 w-4 text-red-500" />
      default:
        return <Clock className="h-4 w-4 text-gray-500" />
    }
  }

  const getStatusBadge = (status) => {
    const variants = {
      verified: 'default',
      updated: 'default',
      completed: 'default',
      pending: 'secondary',
      crawling: 'secondary',
      running: 'secondary',
      failed: 'destructive'
    }
    const labels = {
      verified: '已验证',
      updated: '已更新',
      completed: '已完成',
      pending: '待处理',
      crawling: '爬取中',
      running: '执行中',
      failed: '失败'
    }
    return <Badge variant={variants[status]}>{labels[status]}</Badge>
  }

  // 处理分析结果中的引用链接
  const processAnalysisResult = (text, sources = []) => {
    if (!text) return text

    // 1. 过滤掉 ">" 开头的行
    const lines = text.split('\n')
    const filteredLines = lines.filter(line => !line.trim().startsWith('>'))
    let cleanText = filteredLines.join('\n').trim()

    // 2. 过滤掉"最终数据:"部分（用于AI分析结果）
    const finalDataRegex = /最终数据:\s*\{[^}]*\}/g
    cleanText = cleanText.replace(finalDataRegex, '').trim()

    // 3. 按段落分割
    const paragraphs = cleanText.split(/\n\s*\n/).filter(p => p.trim())
    
    return (
      <div className="prose prose-sm max-w-none space-y-4">
        {paragraphs.map((paragraph, paragraphIndex) => {
          return processParagraph(paragraph, paragraphIndex, sources)
        })}
      </div>
    )
  }

  // 处理单个段落
  const processParagraph = (paragraph, paragraphIndex, sources) => {
    const lines = paragraph.split('\n').filter(line => line.trim())
    
    return (
      <div key={`paragraph-${paragraphIndex}`} className="mb-4">
        {lines.map((line, lineIndex) => {
          return processLine(line, `${paragraphIndex}-${lineIndex}`, sources)
        })}
      </div>
    )
  }

  // 处理单行内容
  const processLine = (line, lineKey, sources) => {
    const trimmedLine = line.trim()
    
    // 处理标题 - 按层级从多到少检查
    if (trimmedLine.startsWith('##### ')) {
      const title = trimmedLine.substring(6)
      return (
        <h5 key={lineKey} className="text-sm font-semibold mt-2 mb-1 text-gray-800">
          {processTextWithReferences(title, lineKey, sources)}
        </h5>
      )
    }
    
    if (trimmedLine.startsWith('#### ')) {
      const title = trimmedLine.substring(5)
      return (
        <h4 key={lineKey} className="text-base font-semibold mt-3 mb-2 text-gray-800">
          {processTextWithReferences(title, lineKey, sources)}
        </h4>
      )
    }
    
    if (trimmedLine.startsWith('### ')) {
      const title = trimmedLine.substring(4)
      return (
        <h3 key={lineKey} className="text-lg font-semibold mt-4 mb-2 text-gray-800">
          {processTextWithReferences(title, lineKey, sources)}
        </h3>
      )
    }
    
    if (trimmedLine.startsWith('## ')) {
      const title = trimmedLine.substring(3)
      return (
        <h2 key={lineKey} className="text-xl font-semibold mt-6 mb-3 text-gray-800">
          {processTextWithReferences(title, lineKey, sources)}
        </h2>
      )
    }

    if (trimmedLine.startsWith('# ')) {
      const title = trimmedLine.substring(2)
      return (
        <h1 key={lineKey} className="text-2xl font-bold mt-8 mb-4 text-gray-800">
          {processTextWithReferences(title, lineKey, sources)}
        </h1>
      )
    }
    
    // 处理列表项
    if (trimmedLine.startsWith('- ')) {
      const content = trimmedLine.substring(2)
      return (
        <div key={lineKey} className="ml-4 mb-1 flex">
          <span className="mr-2">•</span>
          <span>{processTextWithReferences(content, lineKey, sources)}</span>
        </div>
      )
    }
    
    // 处理普通段落
    if (trimmedLine) {
      return (
        <p key={lineKey} className="mb-2 leading-relaxed">
          {processTextWithReferences(trimmedLine, lineKey, sources)}
        </p>
      )
    }
    
    return null
  }

  // 处理文本中的引用和格式
  const processTextWithReferences = (text, lineKey, sources) => {
    // 按句子分割
    const sentences = text.split(/(?<=[。！？])\s*/).filter(s => s.trim())
    
    return sentences.map((sentence, sentenceIndex) => {
      const sentenceKey = `${lineKey}-sentence-${sentenceIndex}`
      
      // 处理粗体
      let processedSentence = sentence.replace(/\*\*(.+?)\*\*/g, (match, content) => {
        return `<BOLD>${content}</BOLD>`
      })
      
      // 查找引用
      const referenceRegex = /\[\[(\d+)\]\]/g
      const parts = []
      let lastIndex = 0
      let match

      while ((match = referenceRegex.exec(processedSentence)) !== null) {
        // 添加引用前的文本
        if (match.index > lastIndex) {
          const textPart = processedSentence.slice(lastIndex, match.index)
          parts.push(textPart)
        }

        const refNumber = parseInt(match[1])
        const source = sources.find(s => s.position === refNumber)
        
        parts.push(`<span class="inline-flex items-center justify-center w-5 h-5 mx-1 bg-gray-400 text-white text-xs rounded-full cursor-pointer hover:bg-blue-500 transition-colors" data-ref="${refNumber}">${refNumber}</span>`)

        lastIndex = match.index + match[0].length
      }

      // 添加剩余文本
      if (lastIndex < processedSentence.length) {
        const textPart = processedSentence.slice(lastIndex)
        parts.push(textPart)
      }
      
      // 合并所有部分
      const combinedText = parts.join('')
      
      return (
        <span 
          key={sentenceKey}
          className={`inline transition-all duration-200 ${
            hoveredSentence === `${lineKey}-${sentenceIndex}`
              ? 'bg-blue-100 text-blue-900 rounded px-1' 
              : ''
          }`}
          dangerouslySetInnerHTML={{ __html: processSimpleFormatting(combinedText, sentenceKey) }}
          onMouseOver={(e) => {
            // 使用 onMouseOver 事件委托处理引用悬停
            const target = e.target
            if (target && target.dataset && target.dataset.ref) {
              const refNumber = parseInt(target.dataset.ref)
              const source = sources.find(s => s.position === refNumber)
              if (source) {
                handleReferenceHover({ 
                  number: refNumber, 
                  source,
                  sentenceIndex: `${lineKey}-${sentenceIndex}`,
                  element: target
                }, e)
              }
            }
          }}
          onMouseMove={(e) => {
            // 实时更新浮框位置跟随鼠标
            if (hoveredReference) {
              const tooltipWidth = 320  // 浮框宽度
              const tooltipHeight = 150 // 浮框高度
              const viewportWidth = window.innerWidth
              const viewportHeight = window.innerHeight
              
              let x = e.clientX + 10 // 鼠标右侧10px
              let y = e.clientY - 10 // 鼠标上方10px
              
              // 如果右侧空间不足，放在左侧
              if (x + tooltipWidth > viewportWidth - 20) {
                x = e.clientX - tooltipWidth - 10
              }
              
              // 如果上方空间不足，放在下方
              if (y < 20) {
                y = e.clientY + 20
              }
              
              // 如果下方空间不足，放在上方
              if (y + tooltipHeight > viewportHeight - 20) {
                y = e.clientY - tooltipHeight - 10
              }
              
              // 确保不会超出屏幕边界
              x = Math.max(10, Math.min(x, viewportWidth - tooltipWidth - 10))
              y = Math.max(10, Math.min(y, viewportHeight - tooltipHeight - 10))
              
              const position = { x, y }
              setTooltipPosition(position)
            }
          }}
          onMouseOut={(e) => {
            // 使用 onMouseOut 事件委托处理引用离开
            const target = e.target
            if (target && target.dataset && target.dataset.ref) {
              // 延迟清除，给用户时间移动到浮框
              setTimeout(() => {
                handleReferenceLeave()
              }, 100)
            }
          }}
          onClick={(e) => {
            // 使用 onClick 事件委托处理引用点击
            const target = e.target
            if (target && target.dataset && target.dataset.ref) {
              const refNumber = parseInt(target.dataset.ref)
              const source = sources.find(s => s.position === refNumber)
              if (source?.link) {
                window.open(source.link, '_blank')
              }
            }
          }}
        />
      )
    })
  }

  // 处理文本格式（粗体、数学公式等）- 返回HTML字符串
  const processTextFormatting = (text, key) => {
    if (!text || typeof text !== 'string') return text
    
    try {
      // 直接使用简单格式化函数，它已经处理了所有格式
      return processSimpleFormatting(text, key)
    } catch (error) {
      console.error('文本格式处理错误:', error)
      return text
    }
  }
  
  // 处理简单格式（粗体和行内公式）- 返回HTML字符串
  const processSimpleFormatting = (text, key) => {
    if (!text || typeof text !== 'string') return text
    
    try {
      let processedText = text
      
      // 处理粗体 **text** 或 <BOLD>text</BOLD>
      const boldRegex1 = /\*\*(.+?)\*\*/g
      const boldRegex2 = /<BOLD>(.+?)<\/BOLD>/g
      
      // 先处理 <BOLD> 标签
      processedText = processedText.replace(boldRegex2, '<strong class="font-semibold text-gray-900">$1</strong>')
      
      // 再处理 ** 格式
      processedText = processedText.replace(boldRegex1, '<strong class="font-semibold text-gray-900">$1</strong>')
      
      // 处理行内数学公式 \( ... \)
      const mathInlineRegex = /\\\(([\s\S]*?)\\\)/g
      processedText = processedText.replace(mathInlineRegex, (match, formula) => {
        return `<span class="inline-flex items-center bg-gray-100 px-2 py-1 rounded text-sm border">${formula.trim()}</span>`
      })
      
      // 处理块级数学公式 \[ ... \]
      const mathBlockRegex = /\\\[([\s\S]*?)\\\]/g
      processedText = processedText.replace(mathBlockRegex, (match, formula) => {
        return `<div class="text-xl bg-white p-6 rounded-lg border-2 border-blue-200 shadow-sm my-4 text-center">${formula.trim()}</div>`
      })
      
      // 始终返回HTML字符串，不返回React元素
      return processedText
    } catch (error) {
      console.error('文本格式处理错误:', error)
      return text
    }
  }

  // 数学公式组件
  const MathFormula = ({ formula, isBlock = false }) => {
    const renderFormula = (formula) => {
      if (!formula || typeof formula !== 'string') {
        return '公式解析错误'
      }
      
      // 处理常见的数学符号和公式
      let processedFormula = formula
        .replace(/CAGR/g, '<span class="font-semibold text-blue-600">CAGR</span>')
        .replace(/FV/g, '<span class="text-green-600 font-semibold">FV</span>')
        .replace(/PV/g, '<span class="text-red-600 font-semibold">PV</span>')
        .replace(/\\frac\{([^}]+)\}\{([^}]+)\}/g, '<div class="inline-block text-center mx-2"><div class="border-b border-gray-600 pb-1 px-2">$1</div><div class="pt-1 px-2">$2</div></div>')
        .replace(/\^(\{[^}]+\}|\w+)/g, '<sup class="text-xs">$1</sup>')
        .replace(/\{([^}]+)\}/g, '$1')
        .replace(/\\left\(/g, '<span class="text-2xl font-light">(</span>')
        .replace(/\\right\)/g, '<span class="text-2xl font-light">)</span>')
        .replace(/\\left/g, '')
        .replace(/\\right/g, '')
        .replace(/\\approx/g, '≈')
        .replace(/\\times/g, '×')
        .replace(/\\div/g, '÷')
        .replace(/\\pm/g, '±')
        
      return processedFormula
    }
    
    if (isBlock) {
      return (
        <div className="text-xl bg-white p-6 rounded-lg border-2 border-blue-200 shadow-sm my-4">
          <div 
            className="text-center flex items-center justify-center"
            style={{ minHeight: '60px' }}
            dangerouslySetInnerHTML={{ __html: renderFormula(formula) }}
          />
        </div>
      )
    } else {
      return (
        <span 
          className="inline-flex items-center bg-gray-100 px-2 py-1 rounded text-sm border"
          dangerouslySetInnerHTML={{ __html: renderFormula(formula) }}
        />
      )
    }
  }

  // 排序功能
  const handleSort = (key) => {
    let direction = 'asc'
    if (sortConfig.key === key && sortConfig.direction === 'asc') {
      direction = 'desc'
    }
    setSortConfig({ key, direction })
    setCurrentPage(1) // 排序后回到第一页
  }

  // 数据处理：筛选 -> 排序 -> 分页
  const processedData = historicalData
    .filter(item =>
      item.business_unit?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.metric_name?.toLowerCase().includes(searchTerm.toLowerCase())
    )
    .sort((a, b) => {
      if (!sortConfig.key) return 0
      
      const aVal = a[sortConfig.key]
      const bVal = b[sortConfig.key]
      
      if (aVal < bVal) return sortConfig.direction === 'asc' ? -1 : 1
      if (aVal > bVal) return sortConfig.direction === 'asc' ? 1 : -1
      return 0
    })

  // 分页数据
  const totalItems = processedData.length
  const totalPages = Math.ceil(totalItems / itemsPerPage)
  const startIndex = (currentPage - 1) * itemsPerPage
  const paginatedData = processedData.slice(startIndex, startIndex + itemsPerPage)

  // 排序图标
  const getSortIcon = (key) => {
    if (sortConfig.key !== key) {
      return <span className="text-gray-400">↕</span>
    }
    return sortConfig.direction === 'asc' ? 
      <span className="text-blue-600">↑</span> : 
      <span className="text-blue-600">↓</span>
  }

  const filteredIndustryData = industryData.filter(item =>
    item.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
    item.source.toLowerCase().includes(searchTerm.toLowerCase())
  )

  // 如果选择了特定板块，显示详情页面
  if (selectedSector) {
    const sectorData = sectorsData[selectedSector]
    const sectorConfig = SECTORS[selectedSector]
    
    return (
      <div className="p-6 space-y-6">
        {/* 返回按钮 */}
        <div className="flex items-center space-x-4">
          <Button 
            variant="outline" 
            onClick={() => {
              setSelectedSector(null)
              // 不需要重置activeTab，保持用户之前的tab选择
            }}
            className="flex items-center"
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            返回
          </Button>
          <div className="flex items-center space-x-3">
            <div className={`w-8 h-8 rounded-full ${sectorConfig.color} flex items-center justify-center text-white text-lg`}>
              {sectorConfig.icon}
            </div>
            <div>
              <h1 className="text-2xl font-bold text-gray-900">{sectorConfig.name}</h1>
              <p className="text-sm text-gray-500">
                {sectorData?.data ? `更新时间: ${formatDateTime(sectorData.data.updated_at)}` : '暂无数据'}
              </p>
            </div>
          </div>
        </div>

        {sectorData?.data ? (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* 左侧：分析结果 */}
            <div className="lg:col-span-2">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center">
                    <Eye className="h-5 w-5 mr-2" />
                    分析结果
                  </CardTitle>
                  <CardDescription>
                    基于最新数据的智能分析结果
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="text-gray-700 leading-relaxed">
                      {processAnalysisResult(sectorData.data.analysis_result, sectorData.data.sources)}
                  </div>
                  
                  {/* AI分析结果分割线和内容 */}
                  {sectorData.data.ai_analysis_result && (
                    <>
                      <div className="mt-8 mb-6">
                        <div className="flex items-center">
                          <div className="flex-1 border-t border-gray-300"></div>
                          <div className="px-4 bg-gradient-to-r from-blue-600 to-purple-600 text-white text-sm font-medium py-2 px-4 rounded-full shadow-md">
                            🤖 AI深度分析
                          </div>
                          <div className="flex-1 border-t border-gray-300"></div>
                        </div>
                      </div>
                      
                      {/* CAGR数据展示 */}
                      <div className="mb-6 grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="bg-blue-50 border border-blue-200 p-4 rounded-lg">
                          <div className="flex items-center mb-2">
                            <div className="w-3 h-3 bg-blue-500 rounded-full mr-2"></div>
                            <h4 className="font-medium text-blue-800">行业复合年增长率</h4>
                          </div>
                          <p className="text-2xl font-bold text-blue-600">
                            {sectorData.data.industry_cagr ? `${sectorData.data.industry_cagr}%` : '暂无数据'}
                          </p>
                          <p className="text-sm text-blue-600 mt-1">2025-2030年预期CAGR</p>
                        </div>
                        
                        <div className="bg-green-50 border border-green-200 p-4 rounded-lg">
                          <div className="flex items-center mb-2">
                            <div className="w-3 h-3 bg-green-500 rounded-full mr-2"></div>
                            <h4 className="font-medium text-green-800">市场阶段影响CAGR</h4>
                          </div>
                          <p className="text-2xl font-bold text-green-600">
                            {sectorData.data.market_stage_cagr ? `${sectorData.data.market_stage_cagr}%` : '暂无数据'}
                          </p>
                          <p className="text-sm text-green-600 mt-1">考虑市场阶段因素后的CAGR</p>
                        </div>
                      </div>
                      
                      {/* AI分析详细内容 */}
                      <AIAnalysisDisplay 
                        analysisResult={sectorData.data.ai_analysis_result}
                        sources={[]}
                      />
                    </>
                  )}
                  
                  {/* 统计信息 */}
                  <div className="mt-6 pt-4 border-t">
                    <div className="flex items-center justify-between text-sm text-gray-500">
                      <span>使用积分: {sectorData.data.credits_used}</span>
                      <span>来源数量: {sectorData.data.sources_count}</span>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 右侧：数据来源 */}
            <div>
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center">
                    <Globe className="h-5 w-5 mr-2" />
                    数据来源
                  </CardTitle>
                  <CardDescription>
                    {sectorData.data.sources_count} 个可靠数据源
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {sectorData.data.sources?.map((source, index) => (
                      <div 
                        key={source.id} 
                        className="p-3 border rounded-lg hover:bg-gray-50 transition-colors cursor-pointer"
                        onClick={() => window.open(source.link, '_blank')}
                      >
                        <div className="flex items-start justify-between">
                          <div className="flex-1">
                            <div className="flex items-center space-x-2 mb-1">
                              <span className="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded">
                                {source.position}
                              </span>
                              <ExternalLink className="h-3 w-3 text-gray-400" />
                            </div>
                            <h4 className="font-medium text-sm text-gray-900 line-clamp-2 mb-2">
                              {source.title}
                            </h4>
                            <p className="text-xs text-gray-600 line-clamp-3 mb-2">
                              {source.snippet}
                            </p>
                            <p className="text-xs text-gray-400">
                              {source.date}
                            </p>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        ) : (
          <Card>
            <CardContent className="flex items-center justify-center h-64">
              <div className="text-center">
                <AlertCircle className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <p className="text-gray-500">该板块暂无数据</p>
                <Button className="mt-4" onClick={() => setShowDemoAlert(true)}>
                  <RefreshCw className="h-4 w-4 mr-2" />
                  刷新数据
                </Button>
              </div>
            </CardContent>
          </Card>
        )}

        {/* 悬浮提示 */}
        {hoveredReference && hoveredReference.element && (
          <div 
            className="fixed z-50 bg-white border border-gray-200 rounded-lg shadow-xl max-w-md transition-all duration-200"
            style={{
              left: `${tooltipPosition.x}px`,
              top: `${tooltipPosition.y}px`,
              transform: 'translate(0, 0)' // 避免额外的变换
            }}
            onMouseEnter={() => {
              // 鼠标进入浮框时，清除离开定时器
              if (hoverTimeoutRef.current) {
                clearTimeout(hoverTimeoutRef.current)
              }
            }}
            onMouseLeave={() => {
              // 鼠标离开浮框时，立即清除悬停状态
              handleReferenceLeave()
            }}
          >
            {/* 小箭头指示器 */}
            <div className="absolute -top-2 left-4 w-4 h-4 bg-white border-l border-t border-gray-200 transform rotate-45"></div>
            
            {/* 内容区域 */}
            <div className="relative p-4">
              <div className="flex items-center mb-2">
                <span className="inline-flex items-center justify-center w-6 h-6 bg-blue-500 text-white text-xs rounded-full mr-2">
                  {hoveredReference.number}
                </span>
                <div className="font-medium text-gray-900">数据来源</div>
              </div>
            {hoveredReference.source && (
              <>
                  <div className="font-medium text-gray-800 mb-2 line-clamp-2">
                    {hoveredReference.source.title}
                  </div>
                  <div className="text-sm text-gray-600 mb-2">
                    {hoveredReference.source.snippet}
                  </div>
                  <div className="flex items-center justify-between text-xs text-gray-500">
                    <span>{hoveredReference.source.date}</span>
                    <ExternalLink className="h-3 w-3" />
                  </div>
              </>
            )}
            </div>
          </div>
        )}
      </div>
    )
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">数据管理</h1>
          <p className="text-gray-600 mt-1">管理历史经营数据和行业数据</p>
        </div>
        <div className="flex space-x-3">
          <Button variant="outline" onClick={() => setShowDemoAlert(true)}>
            <Upload className="h-4 w-4 mr-2" />
            导入数据
          </Button>
          <Button onClick={() => setShowDemoAlert(true)}>
            <Globe className="h-4 w-4 mr-2" />
            爬取行业数据
          </Button>
        </div>
      </div>

      {/* File Upload */}
      <input
        ref={fileInputRef}
        type="file"
        accept=".xlsx,.xls,.csv"
        onChange={handleFileUpload}
        className="hidden"
      />

      {/* Upload Progress */}
      {isUploading && (
        <Card>
          <CardContent className="pt-6">
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium">上传进度</span>
                <span className="text-sm text-gray-500">{uploadProgress}%</span>
              </div>
              <Progress value={uploadProgress} className="w-full" />
            </div>
          </CardContent>
        </Card>
      )}

      {/* Search */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex items-center space-x-4">
            <div className="flex-1">
              <Label htmlFor="search">搜索</Label>
              <div className="relative">
                <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                <Input
                  id="search"
                  placeholder="搜索产品名称、公司或数据源..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>
            <Button variant="outline">
              <Filter className="h-4 w-4 mr-2" />
              筛选
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Data Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
        <TabsList className="grid w-full grid-cols-2 bg-gray-100 p-1 rounded-lg h-14">
          <TabsTrigger 
            value="historical"
            className="flex items-center justify-center px-6 py-3 text-sm font-medium transition-all duration-200 rounded-md hover:bg-white hover:shadow-sm data-[state=active]:bg-white data-[state=active]:shadow-md data-[state=active]:text-blue-600 data-[state=active]:border data-[state=active]:border-blue-200"
          >
            <Database className="h-5 w-5 mr-2" />
            📊 历史经营数据
          </TabsTrigger>
          <TabsTrigger 
            value="industry"
            className="flex items-center justify-center px-6 py-3 text-sm font-medium transition-all duration-200 rounded-md hover:bg-white hover:shadow-sm data-[state=active]:bg-white data-[state=active]:shadow-md data-[state=active]:text-blue-600 data-[state=active]:border data-[state=active]:border-blue-200"
          >
            <Globe className="h-5 w-5 mr-2" />
            🌐 行业数据
          </TabsTrigger>
        </TabsList>

        {/* Historical Data Tab */}
        <TabsContent value="historical">
          <Card>
            <CardHeader>
              <CardTitle>历史经营数据</CardTitle>
              <CardDescription>
                管理和查看四大业务板块的历史经营数据，支持Excel/CSV格式导入
              </CardDescription>
            </CardHeader>
            <CardContent>
              {/* 筛选器 */}
              <div className="flex flex-wrap gap-4 mb-6">
                <div className="flex-1 min-w-[200px]">
                  <label className="block text-sm font-medium text-gray-700 mb-2">业务单元</label>
                  <select
                    value={filters.business_unit}
                    onChange={(e) => setFilters({ ...filters, business_unit: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500"
                  >
                    <option value="">全部业务单元</option>
                    {businessUnits.map((unit) => (
                      <option key={unit} value={unit}>{unit}</option>
                    ))}
                  </select>
                </div>
                <div className="flex-1 min-w-[200px]">
                  <label className="block text-sm font-medium text-gray-700 mb-2">指标类型</label>
                  <select
                    value={filters.metric_name}
                    onChange={(e) => setFilters({ ...filters, metric_name: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500"
                  >
                    <option value="">全部指标</option>
                    {metrics.map((metric) => (
                      <option key={metric} value={metric}>{metric}</option>
                    ))}
                  </select>
                </div>
                <div className="flex-1 min-w-[150px]">
                  <label className="block text-sm font-medium text-gray-700 mb-2">年份</label>
                  <select
                    value={filters.year}
                    onChange={(e) => setFilters({ ...filters, year: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500"
                  >
                    <option value="">全部年份</option>
                    <option value="2021">2021年</option>
                    <option value="2022">2022年</option>
                    <option value="2023">2023年</option>
                    <option value="2024">2024年</option>
                  </select>
                </div>
                <div className="flex items-end">
                  <Button onClick={loadHistoricalData} variant="outline">
                    <RefreshCw className="h-4 w-4 mr-2" />
                    刷新数据
                  </Button>
                </div>
              </div>

              {loading ? (
                <div className="text-center py-8 text-gray-500">
                  加载中...
                </div>
              ) : historicalData.length === 0 ? (
                <div className="text-center py-8 text-gray-500">
                  暂无数据，请先导入历史数据文件
                </div>
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full border-collapse">
                    <thead>
                      <tr className="bg-gray-50">
                        <th 
                          className="px-4 py-3 text-left text-sm font-medium text-gray-900 border-b cursor-pointer hover:bg-gray-100 select-none"
                          onClick={() => handleSort('business_unit')}
                        >
                          <div className="flex items-center justify-between">
                            业务单元
                            {getSortIcon('business_unit')}
                        </div>
                        </th>
                        <th 
                          className="px-4 py-3 text-left text-sm font-medium text-gray-900 border-b cursor-pointer hover:bg-gray-100 select-none"
                          onClick={() => handleSort('metric_name')}
                        >
                          <div className="flex items-center justify-between">
                            指标类型
                            {getSortIcon('metric_name')}
                      </div>
                        </th>
                        <th 
                          className="px-4 py-3 text-center text-sm font-medium text-gray-900 border-b cursor-pointer hover:bg-gray-100 select-none"
                          onClick={() => handleSort('year')}
                        >
                          <div className="flex items-center justify-center">
                            年份
                            {getSortIcon('year')}
                      </div>
                        </th>
                        <th 
                          className="px-4 py-3 text-right text-sm font-medium text-gray-900 border-b cursor-pointer hover:bg-gray-100 select-none"
                          onClick={() => handleSort('value')}
                        >
                          <div className="flex items-center justify-end">
                            数值
                            {getSortIcon('value')}
                    </div>
                        </th>
                        <th className="px-4 py-3 text-center text-sm font-medium text-gray-900 border-b">单位</th>
                        <th 
                          className="px-4 py-3 text-right text-sm font-medium text-gray-900 border-b cursor-pointer hover:bg-gray-100 select-none"
                          onClick={() => handleSort('yoy_growth_rate')}
                        >
                          <div className="flex items-center justify-end">
                            同比增长率
                            {getSortIcon('yoy_growth_rate')}
                    </div>
                        </th>
                        <th 
                          className="px-4 py-3 text-right text-sm font-medium text-gray-900 border-b cursor-pointer hover:bg-gray-100 select-none"
                          onClick={() => handleSort('cagr')}
                        >
                          <div className="flex items-center justify-end">
                            CAGR
                            {getSortIcon('cagr')}
                          </div>
                        </th>
                        <th className="px-4 py-3 text-center text-sm font-medium text-gray-900 border-b">状态</th>
                      </tr>
                    </thead>
                    <tbody>
                      {paginatedData.map((item, index) => (
                        <tr 
                          key={item.id} 
                          className={`${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'} hover:bg-blue-50 transition-colors`}
                        >
                          <td className="px-4 py-3 text-sm font-medium text-gray-900 border-b">
                            {item.business_unit}
                          </td>
                          <td className="px-4 py-3 text-sm text-gray-700 border-b">
                            {item.metric_name}
                          </td>
                          <td className="px-4 py-3 text-sm text-center text-gray-700 border-b">
                            {item.year}
                          </td>
                          <td className="px-4 py-3 text-sm text-right font-medium text-gray-900 border-b">
                            {typeof item.value === 'number' ? item.value.toLocaleString() : item.value}
                          </td>
                          <td className="px-4 py-3 text-sm text-center text-gray-600 border-b">
                            {item.unit}
                          </td>
                          <td className="px-4 py-3 text-sm text-right border-b">
                            {item.yoy_growth_rate ? (
                              <span className={`font-medium ${item.yoy_growth_rate >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                                {item.yoy_growth_rate > 0 ? '+' : ''}{item.yoy_growth_rate}%
                              </span>
                            ) : (
                              <span className="text-gray-400">-</span>
                            )}
                          </td>
                          <td className="px-4 py-3 text-sm text-right border-b">
                            {item.cagr ? (
                              <span className={`font-medium ${item.cagr >= 0 ? 'text-blue-600' : 'text-orange-600'}`}>
                                {item.cagr > 0 ? '+' : ''}{item.cagr}%
                              </span>
                            ) : (
                              <span className="text-gray-400">-</span>
                            )}
                          </td>
                          <td className="px-4 py-3 text-center border-b">
                            <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200 text-xs">
                              已导入
                            </Badge>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                  
                                    {/* 分页控件 */}
                  {totalPages > 1 && (
                    <div className="mt-4 flex items-center justify-between">
                      <div className="text-sm text-gray-600">
                        显示 {startIndex + 1}-{Math.min(startIndex + itemsPerPage, totalItems)} 条，共 {totalItems} 条记录
                      </div>
                      <div className="flex items-center space-x-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                          disabled={currentPage === 1}
                        >
                          上一页
                        </Button>
                        <div className="flex items-center space-x-1">
                          {Array.from({ length: Math.min(totalPages, 5) }, (_, i) => {
                            let pageNum
                            if (totalPages <= 5) {
                              pageNum = i + 1
                            } else if (currentPage <= 3) {
                              pageNum = i + 1
                            } else if (currentPage >= totalPages - 2) {
                              pageNum = totalPages - 4 + i
                            } else {
                              pageNum = currentPage - 2 + i
                            }
                            
                            return (
                              <Button
                                key={pageNum}
                                variant={currentPage === pageNum ? "default" : "outline"}
                                size="sm"
                                className="w-8 h-8 p-0"
                                onClick={() => setCurrentPage(pageNum)}
                              >
                                {pageNum}
                              </Button>
                            )
                          })}
                        </div>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
                          disabled={currentPage === totalPages}
                        >
                          下一页
                        </Button>
                      </div>
                    </div>
                  )}
                  
                  {/* 数据统计信息 */}
                  <div className="mt-4 p-4 bg-gray-50 rounded-lg">
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                      <div>
                        <span className="text-gray-600">总记录数：</span>
                        <span className="font-medium text-gray-900">{totalItems}</span>
                      </div>
                      <div>
                        <span className="text-gray-600">业务单元：</span>
                        <span className="font-medium text-gray-900">{businessUnits.length}</span>
                      </div>
                      <div>
                        <span className="text-gray-600">指标类型：</span>
                        <span className="font-medium text-gray-900">{metrics.length}</span>
                      </div>
                      <div>
                        <span className="text-gray-600">数据年份：</span>
                        <span className="font-medium text-gray-900">2021-2024</span>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Industry Data Tab */}
        <TabsContent value="industry">
          <Card>
            <CardHeader>
              <CardTitle>行业数据</CardTitle>
              <CardDescription>
                四个业务板块的市场数据和预测分析
              </CardDescription>
            </CardHeader>
            <CardContent>
              {loading ? (
                <div className="text-center py-8 text-gray-500">
                  <RefreshCw className="h-8 w-8 animate-spin mx-auto mb-4" />
                  加载中...
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {Object.entries(SECTORS).map(([sectorId, config]) => {
                    const sectorData = sectorsData[sectorId]
                    const hasData = sectorData?.data
                    const status = hasData ? sectorData.data.status : 'pending'
                    
                    return (
                      <div 
                        key={sectorId}
                        className="p-4 border rounded-lg hover:shadow-md transition-shadow cursor-pointer"
                        onClick={() => {
                          setSelectedSector(sectorId)
                          setActiveTab('industry') // 记住当前是在行业数据tab
                        }}
                      >
                        <div className="flex items-center justify-between mb-3">
                          <div className="flex items-center space-x-3">
                            <div className={`w-10 h-10 rounded-full ${config.color} flex items-center justify-center text-white text-xl`}>
                              {config.icon}
                            </div>
                            <div>
                              <h3 className="font-medium text-gray-900">{config.name}</h3>
                              <p className="text-sm text-gray-500">
                                {hasData ? formatDateTime(sectorData.data.updated_at) : '暂无数据'}
                              </p>
                            </div>
                          </div>
                          <div className="flex items-center space-x-2">
                            {getStatusIcon(status)}
                            {getStatusBadge(status)}
                          </div>
                        </div>
                        
                        {hasData && (
                          <div className="text-sm text-gray-600 mb-3">
                            <div className="grid grid-cols-2 gap-4">
                              <div className="bg-blue-50 p-3 rounded-lg">
                                <p className="text-xs text-gray-500 mb-1">行业复合年增长率</p>
                                <p className="text-lg font-semibold text-blue-600">
                                  {sectorData.data.industry_cagr ? `${sectorData.data.industry_cagr}%` : '暂无数据'}
                                </p>
                              </div>
                              <div className="bg-green-50 p-3 rounded-lg">
                                <p className="text-xs text-gray-500 mb-1">市场阶段影响CAGR</p>
                                <p className="text-lg font-semibold text-green-600">
                                  {sectorData.data.market_stage_cagr ? `${sectorData.data.market_stage_cagr}%` : '暂无数据'}
                                </p>
                              </div>
                            </div>
                          </div>
                        )}
                        
                        <div className="flex items-center justify-between text-xs text-gray-500">
                          <span>
                            {hasData ? `${sectorData.data.sources_count} 个数据源` : '等待数据'}
                          </span>
                          <Button variant="ghost" size="sm" className="text-xs">
                            查看详情 →
                          </Button>
                        </div>
                      </div>
                    )
                  })}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 演示模式提示弹窗 */}
      <DemoModeAlert 
        isOpen={showDemoAlert}
        onClose={() => setShowDemoAlert(false)}
        title="导入数据 - 演示模式"
      />
    </div>
  )
}
